package com.easy.controller;

import com.easy.bean.Admin;
import com.easy.bean.User;
import com.easy.service.LoginService;
import com.easy.service.UserService;
import com.easy.util.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin//允许跨域访问
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    LoginService loginService;

    @PostMapping
    public Result add(@RequestBody User user){

        Object obj=userService.add(user);
        return Result.success(obj);
    }
    @PostMapping("/update-password")
    public Result updatePassword(@RequestAttribute("userId") Integer userId,@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword){
        try{
            boolean result = userService.updatePassword(userId, oldPassword, newPassword);
            if( result){
                return Result.success("密码修改成功");
            }else{
                return Result.fail(500,"密码修改失败");
            }
        }catch (Exception e){
            return Result.fail(500,e.getMessage());
        }
    }
    @PostMapping("/reset-password")
    public Result resetPassword(@RequestParam("email") String email,
                                @RequestParam("code") String code,
                                @RequestParam("newPassword") String newPassword) {
        try {
            // 验证邮箱验证码
            if (!EmailCodeUtil.verifyCode(email, code)) {
                return Result.fail(500, "验证码错误或已过期");
            }

            // 获取用户信息
            User user = loginService.getUserByEmail(email);
            if (user == null) {
                return Result.fail(500, "该邮箱未关联任何用户账户");
            }

            // 设置新密码并加密
            String encryptedPassword = PasswordUtil.getEncryption(newPassword);
            user.setPassword(newPassword);
            userService.edit(user);

            return Result.success("密码重置成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500, "密码重置失败：" + e.getMessage());
        }
    }

    @PutMapping
    public Result edit(@RequestBody User user) {
        Object obj = userService.edit(user);
        return Result.success("编辑信息保存成功", obj);
    }

    @DeleteMapping("/{id}")
    public Result del(@PathVariable("id") Integer  id){
        Object obj=userService.del(id);
        return Result.success("删除成功",obj);
    }
    @GetMapping("/{id}")
    public Result one(@RequestAttribute("userId") Integer userId, @RequestAttribute("userRole") String role, @PathVariable("id") Integer  id){

        // 如果不是管理员，只能查看自己的信息
        if (!"admin".equals(role) && !userId.equals(id)) {
            return Result.fail(403, "只能查看自己的信息");
        }
        Object  obj=userService.one(id);
        return Result.success(obj);
    }
    @GetMapping("all")
    public Result all(HttpServletRequest request, User user){
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        Object roleObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ROLE);
        Object idObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);

        // 普通用户只能查看自己的信息
        if (!"admin".equals(roleObj.toString())) {
            user.setId((Integer)idObj);
        }
        Object obj=userService.all( user);
        return Result.success(obj);
    }
    @GetMapping("page")
    public Result page(HttpServletRequest request,Page page,User user){
        //查询一共有多少条数据
        //查询当前页要显示的数据
        //将以上数据封装到page对象中
        //返回page对象
        // 获取当前用户信息
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        Object roleObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ROLE);
        Object idObj = com.easy.util.TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);

        // 普通用户只能查看自己的信息
        if (!"admin".equals(roleObj.toString())) {
            user.setId(Integer.valueOf(idObj.toString()));
        }
        userService.page(page,user);
        return Result.success(page);
    }

}
